<template>
    <Page class="basic company">
        <template #header>
            <el-input v-model="queryForm.productName" placeholder="请输入商品名称" />
            <!-- <EdSelect v-model="queryForm.categoryId" :selectParams="selectGoodsType"></EdSelect> -->
            <EdCascader v-model="queryForm.categoryId" :cascaderParams="selectGoodsType" :filterable="true"></EdCascader>

            <EdSelect v-model="queryForm.publishStatus" :selectParams="selectPublishStatus"></EdSelect>
            <!-- <EdDateTimeRange ref="timeRange" @emit-echo-time-range="emitEchoTimeDate($event, 'pickerTime')"></EdDateTimeRange> -->
            <EdDateTimePickerRange v-model="queryForm.pickerTime"  @emit-echo-time-range="emitEchoTimeDate($event, 'pickerTime')" :pickerParams="pickerRangeParams"></EdDateTimePickerRange>
            <el-button class="ed-button ed_black-bottom" @click="search()"><svg-icon class="svg-middle" icon-class="search-svg"/>查 询</el-button>
            <el-button class="ed-button ed_white_bottom" @click="reset()"><svg-icon icon-class="reset-svg"/>重 置</el-button>
        </template>
        <PageCard title="产品库列表">
            <template #actions>
                <el-button class="ed-button ed_black-bottom ed-button36" @click="batchHandle()" v-has="'shopping:productPool:batchHandle'"><svg-icon icon-class="batch-handle-svg"/>批量处理</el-button>
            </template>
            <ApiTable :api="tableApi" ref="table" :params="queryForm">
                <el-table-column type="index" width="80" label="序号"></el-table-column>
                <!-- <el-table-column width="80" prop="id" label="序号"></el-table-column> -->
                <el-table-column :show-overflow-tooltip="true" prop="productName" label="商品名称" :formatter="formatter"></el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="categoryName" label="商品类别" :formatter="formatter">
                    <!-- <template slot-scope="scope">
                        <span>{{returnName(scope.row['categoryId'], selectGoodsType.options, 'code', 'categoryName') || scope.row['categoryId']}}</span>
                    </template> -->
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="productPrice" label="商品限价" :formatter="formatter_money"></el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="productSellPrice" label="商品售价">
                    <template slot-scope="scope">
                        <div v-if="scope.row['money'] != null">{{ scope.row.money }}元</div>
                        <div v-if="scope.row.moneyPoint['money'] != null">{{ scope.row.moneyPoint['money'] }}元+{{ scope.row.moneyPoint['point'] }}积分</div>
                    </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="surplusStock" label="剩余库存">
                    <template slot-scope="scope">
                        <span>{{ scope.row['surplusStock'] ? scope.row['surplusStock']+'件' : ( scope.row['surplusStock']==0?scope.row['surplusStock']:  '无限制') }}</span>
                    </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建时间" :formatter="formatter"></el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="publishStatus" label="上架/下架">
                    <template slot-scope="scope">
                        {{scope.row.publishStatus == '1' ? '上架' : '下架'}}
                        <el-switch
                            :value="scope.row.publishStatus == '1' ? true : false"
                            @change="switchChange(scope.row, scope.row.publishStatus == '1' ? '0' : '1')"
                            active-color="#EED096"
                            inactive-color="#909399">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="hotStatus" label="设置为热门商品">
                    <template slot-scope="scope">
                        {{scope.row.hotStatus == '1' ? '是' : '否'}}
                        <el-switch
                            :value="scope.row.hotStatus == '1' ? true : false"
                            @change="switchChange_1(scope.row, scope.row.hotStatus == '1' ? '0' : '1')"
                            active-color="#EED096"
                            inactive-color="#909399">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column width="250" :show-overflow-tooltip="true" prop="" label="操作">
                     <template slot-scope="scope">
                        <el-button class="ed-table-bottom ed_black_border" :disabled="scope.row.publishStatus==1" v-has="'shopping:productPool:update'" @click="updateRow(scope.row)">编辑</el-button>
                        <el-button class="ed-table-bottom ed_see_border" v-has="'shopping:productPool:see'" @click="see(scope.row)">查看</el-button>
                    </template>
                </el-table-column>
            </ApiTable>
        </PageCard>
        <EdDialog :width="'474px'" :title="'批量处理'" ref="batchHandleDialog" class="batchHandleDialog" v-if="batchHandleVisible"  @close-dialog="batchHandleClose" @save-dialog="batchHandleSave">
           <div class="content">
                <div class="header">
                    <i class="el-icon-warning" style="color:#EED096;font-size: 18px;"></i>
                    <span>即将批量处理{{bacth_total}}条数据</span>
                </div>
                <div class="main">
                    发布状态&nbsp;
                    <el-radio-group v-model="batch_radio">
                        <el-radio v-for="item in selectPublishStatus.options" :key="item.value" :label="item.value">{{item.label}}</el-radio>
                    </el-radio-group>
                </div>
           </div>
        </EdDialog>
        <EdDialog :width="'819px'" :title="'商品售价编辑'" ref="priceEditDialog" class="priceEditDialog" v-if="priceEditVisible"  @close-dialog="priceEditClose" @save-dialog="priceEditSave('formRef')">
           <el-form ref="formRef" :model="form" label-position="right">
                <el-form-item label="商品名称：">
                    <span>{{currentRow.productName||'-'}}</span>
                </el-form-item>
                <el-form-item label="商品限价：">
                    <span>{{currentRow.productPrice || '-'}}元</span>
                </el-form-item>
                <el-form-item class='money_style' label="商品售价" prop="sell_price" :rules="$validate.validates({required:true,msg:'不能为空'})">
                    <el-col :span="24" style="margin-bottom: 10px">
                        <el-checkbox :value="form.money.length>0?true:false" class="priceCheck_1" @change="checkChange_money">
                            <el-input v-model="form.money" @blur="inputBlur" class="price_input_1" maxlength="11">
                                <i slot="suffix" style="font-style:normal;margin-right: 10px;">元</i>
                            </el-input>
                        </el-checkbox>
                        <div v-show="form.money&&(form.money<currentRow.productPrice)" style="color: #F56C6C; margin-left: 24px">商品售价的价格不能低于商品限价！</div>
                        <div v-show="form.money.length>0&&(!(regFloatTwo.test(form.money))||form.money==0)" style="color: #F56C6C;display: inline-block;margin-left: 24px;">商品售价为小于9位的正数，且最多保留两位有效小数！</div>
                    </el-col>
                    <el-col :span="24" style="margin-bottom: 10px">
                        <el-checkbox :value="form.moneyPoint.money.length>0&&form.moneyPoint.point.length>0?true:false" @change="checkChange_moneyPoint">
                            <el-input v-model="form.moneyPoint.money" @blur="inputBlur" class="price_input_1">
                                <i slot="suffix" style="font-style:normal;margin-right: 10px;" maxlength="11">元</i>
                            </el-input>
                            <i class="el-icon-plus" style="padding-top: 15px; color: #909399"></i>
                            <el-input v-model="form.moneyPoint.point" @blur="inputBlur" class="price_input_1" maxlength="8">
                                <i slot="suffix" style="font-style:normal;margin-right: 10px;">积分</i>
                            </el-input>
                            <span v-show="form.moneyPoint.point&&!(/^[1-9]\d{0,7}$/.test(form.moneyPoint.point))" style="color: #F56C6C;margin-left: 5px">积分为小于9位的正整数！</span>
                        </el-checkbox>
                        <div v-show="form.moneyPoint.money.length>0&&(!(regFloatTwo.test(form.moneyPoint.money))||form.moneyPoint.money==0)" style="color: #F56C6C;display: inline-block;margin-left: 24px;">商品售价为小于9位的正数，且最多保留两位有效小数！</div>
                        <div v-show="form.moneyPoint.money&&(form.moneyPoint.money<currentRow.productPrice)" style="color: #F56C6C; margin-left: 24px">商品售价的价格不能低于商品限价！</div>
                        <div style="color: #C0C4CC;font-size: 12px;">注：商品售价的价格不能低于商品限价，不能使用全积分进行支付</div>
                    </el-col>
                </el-form-item>
                <el-form-item label="服务范围" prop="villageIds">
                    <EdSelect v-model="form.villageIds" :selectParams="selectVillage"></EdSelect>
                </el-form-item>
           </el-form>
        </EdDialog>
    </Page>
</template>

<script>
import Page from '../../components/Page.vue'
import PageCard from 'src/views/components/PageCard.vue'
import ApiTable from 'src/components/ApiTable.vue'
import EdSelect from 'src/components/EdSelect.vue'
import EdCascader from 'src/components/EdCascader.vue'
import EdDateTimeRange from 'src/components/EdDateTimeRange.vue'
import EdDateTimePickerRange from 'src/components/EdDateTimePickerRange.vue'
import EdDialog from 'src/components/EdDialog.vue';
import { defineComponent } from 'vue'
import { productList, productUpdate, productPub, productUnpub, productHot, productUnhot, productBacth, getProjectList, getResourceType, productInfo } from "./api";
import { returnName } from "src/utils/common.js";
import Bus from 'src/utils/Bus';
export default defineComponent({
    name: 'member',
    components: { Page, PageCard, ApiTable, EdSelect, EdDateTimeRange, EdDialog, EdCascader, EdDateTimePickerRange },
    data() {
        return {
            queryForm: {
                productName: '',
                categoryId: '',
                publishStatus: '',
                pickerTime: '',
                startTime: '',
                endTime: '',
            },
            pickerRangeParams:{
                valueFormat:"yyyy-MM-dd HH:mm"
            },
            selectGoodsType:{
                placeholder:"请选择商品类别",
                options: [],
                props: { value: 'code', label: 'categoryName', checkStrictly: true, emitPath: false }
            },
            selectPublishStatus:{
                options: [{
                    value: '1',
                    label: '上架'
                }, {
                    value: '0',
                    label: '下架'
                }],
                placeholder:"请选择商品状态"
            },
            // 批量处理
            batchHandleVisible: false,
            batch_radio: '1',
            bacth_total: '',
            // 编辑
            priceEditVisible: false,
            form: {
                // 商品售价
                money: '',
                // point: '',
                moneyPoint: {
                    money: '',
                    point: '',
                },
                sell_price: [],
                villageIds: [],
            },
            // currentRow: null,
            currentRow: {
                productName: '',
                productPrice: ''
            },
            selectVillage:{
                placeholder:"请选择服务范围",
                options: [],
                props: {label:"villageName", value:"villageId"},
                multiple: true,
                // clearable: true
            },
            point_warning_show: false,
            // 正数、两位有效小数校验
            regFloatTwo: /^(([1-9][0-9]{0,7})|([0]\.\d{1,2})|([1-9][0-9]{0,7}\.\d{1,2}))$/
        }
    },
    activated(){
        // 管理类型
        // getDictByCode('member_user_type').then(res=>{
        //     this.selectParamsUserType.options = res.data.items;
        // })
        // 获取 所属项目
        getProjectList({page: 1, pageSize: 999999}).then(res=>{
            this.selectVillage.options = res.data.records;
        })
        // 商品类别
        getResourceType({pageSize: 999999}).then(res=>{
            this.selectGoodsType.options = res.data;
        })
        this.$nextTick(() => {
            this.$refs.table.load(1);
        })
        // 从详情路由组件 -> 编辑弹框
        Bus.$on('product_goUpdate', (data)=>{
            // console.log('bus---->', data)
            this.updateRow(data);
        })
    },
    methods: {
        tableApi: productList,
        search(){
            // delete this.queryForm['pickerTime'];
            this.$refs.table.load(1)
        },
        reset(){
            this.queryForm = {
                productName: '',
                categoryId: '',
                publishStatus: '',
                pickerTime: '',
                startTime: '',
                endTime: '',
            },
            // this.$refs.timeRange.reset();
            this.$nextTick(() => {
                this.$refs.table.load(1, 10);
            })
        },
        add(){
            this.$router.push({
                path: '/shopping/resourcePool-add'
            })
        },
        // 批量处理
        batchHandle(){
            this.bacth_total = this.$refs.table.page.total;
            this.batchHandleVisible = true;
        },
        batchHandleClose(){
            this.batch_radio = '1';
            this.batchHandleVisible = false;
        },
        batchHandleSave(){
             let params = {
                ...this.queryForm,
                publishType: this.batch_radio,
            }
             productBacth(params).then(response => {
                if(response.success == true) {
                    this.$message.success({
                        message: '处理成功！',
                        duration: 2000,
                        center:true
                    });
                    this.batch_radio = '1';
                    this.batchHandleVisible = false;
                    this.$refs.table.load()
                }
            }).catch(()=>{
                this.$refs.batchHandleDialog.hideLoading()
            })
        },
        // 编辑
        updateRow(row){
            productInfo({id: row.id}).then(response => {
                if(response.success == true) {
                    this.currentRow=response.data;
                    this.form.money = response.data.money !=null ? response.data.money.toString() : '';
                    // this.form.moneyPoint = response.data.moneyPoint;
                    this.form.moneyPoint.money = response.data.moneyPoint.money != null ? response.data.moneyPoint.money.toString() : '';
                    this.form.moneyPoint.point = response.data.moneyPoint.point != null ? response.data.moneyPoint.point.toString() : '';

                    this.form.villageIds = response.data.villageIds.length ? response.data.villageIds.toString().split(',') : [];
                    this.form.sell_price.push(response.data.money, response.data.moneyPoint.money);
                    this.priceEditVisible = true;
                }
            })
        },
        priceEditSave(formName){
            this.$refs[formName].validate((valid) => {
                if(valid){
                    if(this.form.money.length==0 && this.form.moneyPoint.money.length==0) {
                        this.$refs.priceEditDialog.hideLoading()
                        return this.$message.error({ message: '请填写商品售价！！', center: true });
                    }else if(this.form.moneyPoint.money.length!=0&&this.form.moneyPoint.point.length==0 || this.form.moneyPoint.money.length==0&&this.form.moneyPoint.point.length!=0){
                        this.$refs.priceEditDialog.hideLoading()
                        return this.$message.error({ message: '商品售价选择金额加积分时，两者都必填！', center: true });
                    }else if (this.form.money.length>0&&(!(this.regFloatTwo.test(this.form.money))||this.form.money==0) || this.form.moneyPoint.money.length>0&&(!(this.regFloatTwo.test(this.form.moneyPoint.money))||this.form.moneyPoint.money==0)){
                        // 售价：整数、两位小数
                        this.$refs.priceEditDialog.hideLoading()
                        return this.$message.error({ message: '商品商品售价为小于9位的正数，且最多保留两位有效小数！', center: true })
                    }else if(this.form.moneyPoint.point&&!(/^[1-9]\d{0,7}$/.test(this.form.moneyPoint.point))){
                        // 积分为小于9位的正整数
                        this.$refs.priceEditDialog.hideLoading()
                        return this.$message.error({ message: '积分为小于9位的正整数！', center: true })
                    }
                    let params = {
                        id:  this.currentRow.id,
                        money: this.form.money,
                        moneyPoint: this.form.moneyPoint,
                        villageIds: this.form.villageIds,
                    }

                    // console.log('编辑 params--->', params)
                    // return
                    productUpdate(params).then(response => {
                        if(response.success == true) {
                            this.$message.success({
                                message: '操作成功！',
                                duration: 2000,
                                center:true
                            });
                            this.priceEditVisible = false;
                            this.$refs.table.load()
                        }
                    }).catch(()=>{
                        this.$refs.priceEditDialog.hideLoading()
                    })
                }else{
                    this.$refs.priceEditDialog.hideLoading()
                }
            })
        },
        priceEditClose(){
            this.form = {
                // 商品售价
                money: '',
                point: '',
                moneyPoint: {
                    money: '',
                    point: '',
                },
                sell_price: [],
                villageIds: [],
            }
            this.priceEditVisible = false;
            this.$refs.formRef.resetFields()
        },
        // 编辑 checkbox - change
        checkChange_money(val){
            if(!val) this.form.money = '';
        },
        checkChange_moneyPoint(val){
            if(!val) this.form.moneyPoint = {money: '', point: ''};
        },
        inputBlur(e){
            // if(e.target.value) this.form.sell_price.money = e.target.value;
            if(e.target.value) this.form.sell_price.push(e.target.value);
        },
        inputBlur_2(e){
            if(e.target.value){
                let reg = /^[1-9]\d*$/;
                const is_true = reg.test(e.target.value)
                if(!is_true){
                    // 积分为整数
                    this.point_warning_show = true
                }else{
                    this.form.sell_price.push(e.target.value);
                    this.point_warning_show = false
                }
            }else{
                this.point_warning_show = false
            }
        },
        // 上架/下架
        switchChange(row, value){
            let params = {
                id: row.id,
                // publishStatus: value,
            }
            let fucApi = value == 1 ? productPub : productUnpub;
            fucApi(params).then(res => {
                if(res.success == true){
                    this.$message.success({
                        message: '操作成功',
                        duration: 2000,
                        center:true
                    })
                    this.$refs.table.load()
                }
            })
        },
        // 是否是热门商品
        switchChange_1(row, value){
            let params = {
                id: row.id,
                // hotProduct: value,
            }
            let fucApi = value == 1 ? productHot : productUnhot;

            fucApi(params).then(res => {
                if(res.success == true){
                    this.$message.success({
                        message: '操作成功',
                        duration: 2000,
                        center:true
                    })
                    this.$refs.table.load()
                }
            })
        },
        returnName(val, options, value, label){
            return returnName(val, options, value, label)
        },
        emitEchoTimeDate(data){
            // $event 子组件$emit传的参数 
            this.queryForm['startTime'] = data.startTime;
            this.queryForm['endTime'] = data.endTime;
        },
        // 查看
        see(row){
            this.$router.push({
                path: '/shopping/productPool-detail',
                query: { id: row.id },
            })
        },
        formatter(row, column, cellValue, index){
            return cellValue || '-'
        },
        formatter_money(row, column, cellValue, index){
            return cellValue +'元' ||  '-'
        },
    }
})
</script>

<style scoped lang="scss">
    :deep .batchHandleDialog{
        font-family: 'PingFang SC';
        font-style: normal;
        font-weight: 400;
        font-size: 18px;
        .el-dialog__body{
            padding-left: 75px;
        }
        .header{
            color: #1E1E1E;
            margin-bottom: 30px;
        }
        .main{
            color: #606266;
        }
        .el-radio-group .el-radio.is-checked{
            .el-radio__input{
                .el-radio__inner{
                    border-color: #EED096;
                    background: #EED096;
                }
            }
            .el-radio__label{
                color: #EED096;
            }
        }

        .el-radio-group .el-radio{
            .el-radio__input{
                .el-radio__inner:hover{
                    border-color: #EED096;
                }
            }
        }
    }

    :deep .priceEditDialog{
        .el-dialog__body{
            padding-left: 75px;
            .el-select{
                width: 50%;
                .el-input{
                    width: 100%;
                }
            }
            .el-input{
                width: 50%;
            }
            .el-checkbox__label  .el-input{
                width: 230px;
            }
            .el-checkbox__input{
                // margin-top: 15px;
            }
            .priceCheck_1 .el-checkbox__input{
                // margin-top: 15px;
            }

            .el-checkbox.is-checked{
                .el-checkbox__input{
                    .el-checkbox__inner{
                        border-color: #EED096;
                        background: #EED096;
                    }
                }
                .el-checkbox__label{
                    color: #EED096;
                }
            }
            .el-checkbox{
                .el-checkbox__input.is-focus{
                    .el-checkbox__inner{
                        border-color: #EED096;
                    }
                }
                .el-checkbox__label{
                    color: #EED096;
                }
            }

            .el-checkbox{
                .el-checkbox__input{
                    .el-checkbox__inner:hover{
                        border-color: #EED096;
                    }
                }
            }   

            .el-input-group__append{
                width: 55px !important;
                padding: 0 !important;
                text-align: center !important;
            }

            .money_style{
                .el-input__suffix-inner{
                    display: inline-block;
                    margin-top: 10px;
                }
            }
        }
    }
</style>